local json = require "cjson.safe"
local http = require "resty.http"

local function record_visit_data(premature, record)
    if not premature then
        local httpc = http.new()
        local res, err = httpc:request_uri('http://192.168.1.103:7932/api/Operation/UpdateActionRequest?ControllerName=' .. record.ControllerName ..'&ActionName='..record.ActionName, {
            method = "POST",
            keepalive_timeout = 2000 -- 毫秒
        })

        if (not res) or (res.status == 502) then
            if not res then
                ngx.log(ngx.ERR, "请求出错#", err)
            else
                ngx.log(ngx.ERR, "请求出错 header status=502")
            end
            
        else
            --ngx.log(ngx.ERR, '更新结果', res.body)
            local json_data = json.decode(res.body).data
            return json_data
        end
        
    end
end
--split来源   https://blog.csdn.net/heyuchang666/article/details/52403087
local function split(input, delimiter)
    input = tostring(input)
    delimiter = tostring(delimiter)
    if (delimiter=='') then return false end
    local pos,arr = 0, {}
    -- for each divider found
    for st,sp in function() return string.find(input, delimiter, pos, true) end do
        table.insert(arr, string.sub(input, pos, st - 1))
        pos = sp + 1
    end
    table.insert(arr, string.sub(input, pos))
    return arr
end




local ua = ngx.ctx.ua;

local request_method = ngx.var.request_method

local req_method
local req_param

if request_method == 'GET' then
    req_method = 0
    req_param = ngx.var.args
elseif request_method == 'POST' then
    req_method = 1
    req_param = ngx.req.get_body_data()
elseif request_method == 'PUT' then
    req_method = 2
elseif request_method == 'DELETE' then
    req_method = 3
elseif request_method == 'OPTION' then
    req_method = 4
else
    req_method = 5
end
local tmp = (string.gsub(ngx.var.uri, "?.*", ""))
tmp = string.lower(tmp)
tmp = (string.gsub(tmp, '/api/', ""))
 

local res = split(tmp, "/")
-- ngx.log(ngx.ERR, "当前请求的url#" ..json.encode(res) )
-- ngx.log(ngx.ERR, "当前请求的controller#" ..res[1] )
-- ngx.log(ngx.ERR, "当前请求的action#" ..res[2] )
-- ngx.log(ngx.ERR, "当前请求的url#" ..tmp )
local record = {
    url = ngx.var.uri,
    ControllerName = res[1],
    ActionName = res[2],
}

-- 判断 是否需要调监听的接口(不做)
--记录返回的结果




local ok, err = ngx.timer.at(0, record_visit_data, record)
if not ok then
    ngx.log(ngx.ERR, "failed to create record_visit_data timer#", json.encode(record), ", err#", err)
    return
end